import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CoreWechatReplyService extends BaseService<any> {
  private readonly logger = new Logger(CoreWechatReplyService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * getKeywordPage
   * 对应 PHP: CoreWechatReplyService_core::getKeywordPage()
   * 逻辑类型: undefined - undefined
   */
  async getKeywordPage(site_id: any[], data: any[]) {
    // 基于PHP真实逻辑: getKeywordPage
    // PHP原文: $where = [             ['site_id', '=', $site_id],             ['reply_type', '=', WechatDict::REPLY_KEYWORD]         ];         if (!empty($data['key...
const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD]
        ];
        if (!!data.keyword)) {
            where[] = ['keyword', 'like', '%' . data.keyword  + '%'];
  }

  /**
   * getKeywordInfo
   * 对应 PHP: CoreWechatReplyService_core::getKeywordInfo()
   * 逻辑类型: undefined - undefined
   */
  async getKeywordInfo(site_id: number, id: number) {
    // 基于PHP真实逻辑: getKeywordInfo
    // PHP原文: return $this->model->where([             ['site_id', '=', $site_id],             ['id', '=', $id],             ['reply_type', '=', WechatDict::REPLY_K...
return this.model.where([
            ['site_id', '=', site_id],
            ['id', '=', id],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD))
        ).findOrEmpty().toArray(];
    }

    /**
     * 通过关键词查询回复
     * @param int site_id
     * @param string keyword
     * @return void
     * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getKeywordInfoByKeyword(int site_id, string keyword)
    {
        const list = this.model.where([
            ['site_id', '=', site_id],
            ['keyword', 'like', '%' . keyword  + '%'],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD)),
        ).order('sort asc').select().toArray(];
        if (!!list)) {
            foreach (list as v) {
                const item_keyword = v.keyword;
                switch (v.matching_type) {
                    case ReplyDict.MATCHING_TYPE_FULL://全匹配
                        const item_keyword === keyword && reply_content = item_keyword;
                        break;
                    case ReplyDict.MATCHING_TYPE_LIKE://模糊匹配
                        stripos(item_keyword, keyword) !== false && reply_content = item_keyword;
                        break;
                }
                if (!!reply_content)) {
                    return v;
                }
            }
  }

  /**
   * getKeywordInfoByKeyword
   * 对应 PHP: CoreWechatReplyService_core::getKeywordInfoByKeyword()
   * 逻辑类型: undefined - undefined
   */
  async getKeywordInfoByKeyword(site_id: number, keyword: number) {
    // 基于PHP真实逻辑: getKeywordInfoByKeyword
    // PHP原文: $list = $this->model->where([             ['site_id', '=', $site_id],             ['keyword', 'like', '%' . $keyword . '%'],             ['reply_type'...
const list = this.model.where([
            ['site_id', '=', site_id],
            ['keyword', 'like', '%' . keyword  + '%'],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD)),
        ).order('sort asc').select().toArray(];
        if (!!list)) {
            foreach (list as v) {
                const item_keyword = v.keyword;
                switch (v.matching_type) {
                    case ReplyDict.MATCHING_TYPE_FULL://全匹配
                        const item_keyword === keyword && reply_content = item_keyword;
                        break;
                    case ReplyDict.MATCHING_TYPE_LIKE://模糊匹配
                        stripos(item_keyword, keyword) !== false && reply_content = item_keyword;
                        break;
                }
                if (!!reply_content)) {
                    return v;
                }
            }
  }

  /**
   * addKeyword
   * 对应 PHP: CoreWechatReplyService_core::addKeyword()
   * 逻辑类型: undefined - undefined
   */
  async addKeyword(site_id: any[], data: any[]) {
    // 基于PHP真实逻辑: addKeyword
    // PHP原文: $data['site_id'] = $site_id;         $data['reply_type'] = WechatDict::REPLY_KEYWORD;         $this->model->create($data);         return true;     } ...
data.site_id = site_id;
        data.reply_type = WechatDict.REPLY_KEYWORD;
        this.model.create(data);
        return true;
    }

    /**
     * 更新关键词回复
     * @param int site_id
     * @param int id
     * @param data
     * @return WechatReply
     */
    async editKeyword(int site_id, int id, data)
    {
        const where = [
            ['site_id', '=', site_id],
            ['id', '=', id],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD]
        ];
        return this.model.update(data, where);
    }

    /**
     * 删除关键词回复
     * @return void
     */
    async delKeyword(int site_id, int id)
    {
        const where = [
            ['site_id', '=', site_id],
            ['id', '=', id],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD)
        ];
        const reply = this.find(where);
        if (reply.isEmpty())
            throw new AdminBusinessException('KEYWORDS_NOT_EXIST'];
        return reply.delete();
    }

    /**
     *
     * @param array|string where
     * @return WechatReply|array|mixed|Model
     */
    async find(array|string where)
    {
        return this.model.where(where).findOrEmpty(];
    }


    /**
     * 获取默认回复
     * @param int site_id
     * @return */
    async getDefault(int site_id)
    {
        return this.model.where([
                ['site_id', '=', site_id],
                ['reply_type', '=', WechatDict.REPLY_DEFAULT)
            )
        ).findOrEmpty().toArray(];
    }

    /**
     * 更新默认回复
     * @param int site_id
     * @param data
     * @return void
     */
    async editDefault(int site_id, data)
    {
        const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_DEFAULT]
        ];
        const reply = this.find(where);
        //如果不存在,则创建一条默认回复记录
        if (reply.isEmpty()) {
            data.reply_type = WechatDict.REPLY_DEFAULT;
            data.site_id = site_id;
            return this.model.create(data);
  }

  /**
   * editKeyword
   * 对应 PHP: CoreWechatReplyService_core::editKeyword()
   * 逻辑类型: undefined - undefined
   */
  async editKeyword(site_id: any[], id: any[], data: any[]) {
    // 基于PHP真实逻辑: editKeyword
    // PHP原文: $where = [             ['site_id', '=', $site_id],             ['id', '=', $id],             ['reply_type', '=', WechatDict::REPLY_KEYWORD]         ];...
const where = [
            ['site_id', '=', site_id],
            ['id', '=', id],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD]
        ];
        return this.model.update(data, where);
    }

    /**
     * 删除关键词回复
     * @return void
     */
    async delKeyword(int site_id, int id)
    {
        const where = [
            ['site_id', '=', site_id],
            ['id', '=', id],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD)
        ];
        const reply = this.find(where);
        if (reply.isEmpty())
            throw new AdminBusinessException('KEYWORDS_NOT_EXIST'];
        return reply.delete();
    }

    /**
     *
     * @param array|string where
     * @return WechatReply|array|mixed|Model
     */
    async find(array|string where)
    {
        return this.model.where(where).findOrEmpty(];
    }


    /**
     * 获取默认回复
     * @param int site_id
     * @return */
    async getDefault(int site_id)
    {
        return this.model.where([
                ['site_id', '=', site_id],
                ['reply_type', '=', WechatDict.REPLY_DEFAULT)
            )
        ).findOrEmpty().toArray(];
    }

    /**
     * 更新默认回复
     * @param int site_id
     * @param data
     * @return void
     */
    async editDefault(int site_id, data)
    {
        const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_DEFAULT]
        ];
        const reply = this.find(where);
        //如果不存在,则创建一条默认回复记录
        if (reply.isEmpty()) {
            data.reply_type = WechatDict.REPLY_DEFAULT;
            data.site_id = site_id;
            return this.model.create(data);
  }

  /**
   * delKeyword
   * 对应 PHP: CoreWechatReplyService_core::delKeyword()
   * 逻辑类型: undefined - undefined
   */
  async delKeyword(site_id: number, id: number) {
    // 基于PHP真实逻辑: delKeyword
    // PHP原文: $where = array(             ['site_id', '=', $site_id],             ['id', '=', $id],             ['reply_type', '=', WechatDict::REPLY_KEYWORD]      ...
const where = [
            ['site_id', '=', site_id],
            ['id', '=', id],
            ['reply_type', '=', WechatDict.REPLY_KEYWORD)
        ];
        const reply = this.find(where);
        if (reply.isEmpty())
            throw new AdminBusinessException('KEYWORDS_NOT_EXIST'];
        return reply.delete();
    }

    /**
     *
     * @param array|string where
     * @return WechatReply|array|mixed|Model
     */
    async find(array|string where)
    {
        return this.model.where(where).findOrEmpty(];
    }


    /**
     * 获取默认回复
     * @param int site_id
     * @return */
    async getDefault(int site_id)
    {
        return this.model.where([
                ['site_id', '=', site_id],
                ['reply_type', '=', WechatDict.REPLY_DEFAULT)
            )
        ).findOrEmpty().toArray(];
    }

    /**
     * 更新默认回复
     * @param int site_id
     * @param data
     * @return void
     */
    async editDefault(int site_id, data)
    {
        const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_DEFAULT]
        ];
        const reply = this.find(where);
        //如果不存在,则创建一条默认回复记录
        if (reply.isEmpty()) {
            data.reply_type = WechatDict.REPLY_DEFAULT;
            data.site_id = site_id;
            return this.model.create(data);
  }

  /**
   * findRecord (原方法名: find)
   * 对应 PHP: CoreWechatReplyService_core::find()
   * 逻辑类型: undefined - undefined
   * 注意: 为避免与BaseService方法冲突，已重命名
   */
  async findRecord(where: any[]) {
    // 基于PHP真实逻辑: find
    // PHP原文: return $this->model->where($where)->findOrEmpty();     }       /**      * 获取默认回复      * @param int $site_id      * @return array      */     public fu...
return this.model.where(where).findOrEmpty(];
    }


    /**
     * 获取默认回复
     * @param int site_id
     * @return */
    async getDefault(int site_id)
    {
        return this.model.where([
                ['site_id', '=', site_id],
                ['reply_type', '=', WechatDict.REPLY_DEFAULT)
            )
        ).findOrEmpty().toArray(];
    }

    /**
     * 更新默认回复
     * @param int site_id
     * @param data
     * @return void
     */
    async editDefault(int site_id, data)
    {
        const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_DEFAULT]
        ];
        const reply = this.find(where);
        //如果不存在,则创建一条默认回复记录
        if (reply.isEmpty()) {
            data.reply_type = WechatDict.REPLY_DEFAULT;
            data.site_id = site_id;
            return this.model.create(data);
  }

  /**
   * getDefault
   * 对应 PHP: CoreWechatReplyService_core::getDefault()
   * 逻辑类型: undefined - undefined
   */
  async getDefault(site_id: number) {
    // 基于PHP真实逻辑: getDefault
    // PHP原文: return $this->model->where([                 ['site_id', '=', $site_id],                 ['reply_type', '=', WechatDict::REPLY_DEFAULT]             ] ...
return this.model.where([
                ['site_id', '=', site_id],
                ['reply_type', '=', WechatDict.REPLY_DEFAULT)
            )
        ).findOrEmpty().toArray(];
    }

    /**
     * 更新默认回复
     * @param int site_id
     * @param data
     * @return void
     */
    async editDefault(int site_id, data)
    {
        const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_DEFAULT]
        ];
        const reply = this.find(where);
        //如果不存在,则创建一条默认回复记录
        if (reply.isEmpty()) {
            data.reply_type = WechatDict.REPLY_DEFAULT;
            data.site_id = site_id;
            return this.model.create(data);
  }

  /**
   * editDefault
   * 对应 PHP: CoreWechatReplyService_core::editDefault()
   * 逻辑类型: undefined - undefined
   */
  async editDefault(site_id: any[], data: any[]) {
    // 基于PHP真实逻辑: editDefault
    // PHP原文: $where = [             ['site_id', '=', $site_id],             ['reply_type', '=', WechatDict::REPLY_DEFAULT]         ];         $reply = $this->find(...
const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_DEFAULT]
        ];
        const reply = this.find(where);
        //如果不存在,则创建一条默认回复记录
        if (reply.isEmpty()) {
            data.reply_type = WechatDict.REPLY_DEFAULT;
            data.site_id = site_id;
            return this.model.create(data);
  }

  /**
   * getSubscribe
   * 对应 PHP: CoreWechatReplyService_core::getSubscribe()
   * 逻辑类型: undefined - undefined
   */
  async getSubscribe(site_id: number) {
    // 基于PHP真实逻辑: getSubscribe
    // PHP原文: return $this->model->where([                 ['site_id', '=', $site_id],                 ['reply_type', '=', WechatDict::REPLY_SUBSCRIBE]             ...
return this.model.where([
                ['site_id', '=', site_id],
                ['reply_type', '=', WechatDict.REPLY_SUBSCRIBE)
            )
        ).findOrEmpty().toArray(];
    }

    /**
     * 更新关注回复
     * @param int site_id
     * @param data
     * @return void
     */
    async editSubscribe(int site_id, data)
    {
        const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_SUBSCRIBE]
        ];
        const reply = this.find(where);
        //如果不存在,则创建一条关注回复记录
        if (reply.isEmpty()) {
            data.reply_type = WechatDict.REPLY_SUBSCRIBE;
            data.site_id = site_id;
            return this.model.create(data);
  }

  /**
   * editSubscribe
   * 对应 PHP: CoreWechatReplyService_core::editSubscribe()
   * 逻辑类型: undefined - undefined
   */
  async editSubscribe(site_id: any[], data: any[]) {
    // 基于PHP真实逻辑: editSubscribe
    // PHP原文: $where = [             ['site_id', '=', $site_id],             ['reply_type', '=', WechatDict::REPLY_SUBSCRIBE]         ];         $reply = $this->fin...
const where = [
            ['site_id', '=', site_id],
            ['reply_type', '=', WechatDict.REPLY_SUBSCRIBE]
        ];
        const reply = this.find(where);
        //如果不存在,则创建一条关注回复记录
        if (reply.isEmpty()) {
            data.reply_type = WechatDict.REPLY_SUBSCRIBE;
            data.site_id = site_id;
            return this.model.create(data);
  }

  /**
   * reply
   * 对应 PHP: CoreWechatReplyService_core::reply()
   * 逻辑类型: undefined - undefined
   */
  async reply(site_id: number, event: number, content: number, openid: number) {
    // 基于PHP真实逻辑: reply
    // PHP原文: switch ($event) {             case WechatDict::REPLY_SUBSCRIBE://关注回复                 $info = $this->getSubscribe($site_id);                 break;   ...
switch (event) {
            case WechatDict.REPLY_SUBSCRIBE://关注回复
                const info = this.getSubscribe(site_id];
                break;
            case WechatDict.REPLY_KEYWORD://关键词回复
                const info = this.getKeywordInfoByKeyword(site_id, content);
                break;
  }

  /**
   * sendCustomMessage
   * 对应 PHP: CoreWechatReplyService_core::sendCustomMessage()
   * 逻辑类型: undefined - undefined
   */
  async sendCustomMessage(site_id: any[], options: any[]) {
    // 基于PHP真实逻辑: sendCustomMessage
    // PHP原文: $send_res = CoreWechatService::appApiClient($site_id)->post('/cgi-bin/message/custom/send', [             'json' => $options         ]);         if (i...
const send_res = CoreWechatService.appApiClient(site_id).post('/cgi-bin/message/custom/send', [
            json: options
        )];
        if (typeof send_res.errcode) && send_res.errcode != 0) {
            Log.write(send_res.errmsg);
  }
}
